package com.wyix.dao;

import com.wyix.domain.Order;
import com.wyix.domain.Product;
import com.wyix.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

/**
 * @author wangdx
 * @since 2025/8/22
 */
public class OrderDAO {
    private UserDAO userDAO = new UserDAO();
    private ProductDAO productDAO = new ProductDAO();

    /**
     * 创建订单（包含事务管理）
     * 这个操作需要同时更新用户余额、商品库存和创建订单
     * @param userId 用户ID
     * @param productId 商品ID
     * @param quantity 购买数量
     * @return 创建成功返回订单对象，否则返回null
     */
    public Order createOrder(int userId, int productId, int quantity) {
        Connection conn = null;
        try {
            // 获取连接
            conn = DBUtil.getConnection();
            // 关闭自动提交，开启事务
            conn.setAutoCommit(false);

            // 1. 查询商品信息
            Product product = productDAO.findById(productId);
            if (product == null) {
                throw new SQLException("商品不存在");
            }

            // 2. 计算总金额
            double totalAmount = product.getPrice() * quantity;

            // 3. 检查并扣减用户余额
            boolean balanceUpdated = userDAO.updateBalance(conn, userId, -totalAmount);
            if (!balanceUpdated) {
                throw new SQLException("用户余额不足或更新失败");
            }

            // 4. 检查并减少商品库存
            boolean stockReduced = productDAO.reduceStock(conn, productId, quantity);
            if (!stockReduced) {
                throw new SQLException("商品库存不足或更新失败");
            }

            // 5. 创建订单
            String orderNo = generateOrderNo();
            Order order = new Order(orderNo, userId, productId, quantity, totalAmount);

            String sql = "INSERT INTO `order`(order_no, user_id, product_id, quantity, total_amount, create_time, status) " +
                    "VALUES(?, ?, ?, ?, ?, ?, ?)";

            try (PreparedStatement pstmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
                pstmt.setString(1, order.getOrderNo());
                pstmt.setInt(2, order.getUserId());
                pstmt.setInt(3, order.getProductId());
                pstmt.setInt(4, order.getQuantity());
                pstmt.setDouble(5, order.getTotalAmount());
                pstmt.setTimestamp(6, new java.sql.Timestamp(order.getCreateTime().getTime()));
                pstmt.setString(7, order.getStatus());

                int rows = pstmt.executeUpdate();
                if (rows <= 0) {
                    throw new SQLException("创建订单失败");
                }

                // 获取自动生成的订单ID
                try (ResultSet rs = pstmt.getGeneratedKeys()) {
                    if (rs.next()) {
                        order.setId(rs.getInt(1));
                    }
                }
            }

            // 所有操作成功，提交事务
            conn.commit();
            return order;

        } catch (SQLException e) {
            e.printStackTrace();
            // 发生异常，回滚事务
            if (conn!= null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            return null;
        } finally {
            // 关闭连接
            DBUtil.closeConnection(conn);
        }
    }

    /**
     * 生成唯一订单号
     * @return 订单号字符串
     */
    private String generateOrderNo() {
        // 使用UUID和时间戳生成唯一订单号
        return "ORD" + System.currentTimeMillis() +
                UUID.randomUUID().toString().substring(0, 8).toUpperCase();
    }

    /**
     * 根据订单号查询订单
     * @param orderNo 订单号
     * @return 订单对象，如果不存在则返回null
     */
    public Order findByOrderNo(String orderNo) {
        String sql = "SELECT * FROM `order` WHERE order_no = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, orderNo);

            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    Order order = new Order();
                    order.setId(rs.getInt("id"));
                    order.setOrderNo(rs.getString("order_no"));
                    order.setUserId(rs.getInt("user_id"));
                    order.setProductId(rs.getInt("product_id"));
                    order.setQuantity(rs.getInt("quantity"));
                    order.setTotalAmount(rs.getDouble("total_amount"));
                    order.setCreateTime(rs.getTimestamp("create_time"));
                    order.setStatus(rs.getString("status"));
                    return order;
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 更新订单状态
     * @param orderId 订单ID
     * @param status 新状态
     * @return 更新成功返回true，否则返回false
     */
    public boolean updateOrderStatus(int orderId, String status) {
        String sql = "UPDATE `order` SET status = ? WHERE id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, status);
            pstmt.setInt(2, orderId);

            int rows = pstmt.executeUpdate();
            return rows > 0;

        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
}
